<template>
    <div style="margin-top: 12px;">
        <TitleTips title="养护明细">
            <BaseButton slot="button" :disabled="cardList.length >= 20" plain @click="handleAdd">新增分组</BaseButton>
        </TitleTips>
        <CardBox v-for="(item, index) in cardList" :key="item.fid" :title="`分组${index + 1}`" style="padding-bottom: 32px">
            <BaseButton v-if="cardList.length > 1" slot="button" type="text" color="danger" icon="el-icon-delete" @click="handleDelete(index)">
                删除
            </BaseButton>
            <el-form ref="form" :model="item" :rules="rules" size="medium" label-width="110px">
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="位置类型" prop="locationType">
                                <el-radio-group v-model="item.locationType">
                                    <el-radio :label="1">桩号</el-radio>
                                    <el-radio :label="2">桩号范围</el-radio>
                                    <el-radio :label="3">位置描述</el-radio>
                                </el-radio-group>
                            </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <!-- 位置描述 -->
                        <el-col v-if="item.locationType === 3" :xl="6" :lg="8" style="padding: 0">
                            <el-form-item label="桩号部位" prop="locationDescription">
                                <el-input v-model="item.locationDescription" placeholder="请输入" maxlength="50" show-word-limit clearable>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <!-- 桩号和桩号范围的方向-->
                        <el-col v-else :xl="3" :lg="5" :md="8" style="padding: 0">
                            <el-form-item label="桩号部位" prop="direction">
                                <el-select v-model="item.direction" placeholder="请选择" clearable style="width: 100%;">
                                    <el-option v-for="d in directionOptions" :key="d.value" :label="d.label" :value="d.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <!-- 桩号 -->
                        <template v-if="item.locationType === 1">
                            <div style="padding-left: 14px;width: 168px;display: inline-block;">
                                <el-form-item label="" prop="stake1" label-width="0">
                                    <el-input
                                        v-model.trim="item.stake1"
                                        placeholder="请输入"
                                        maxlength="3"
                                        @change="item.stake2 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </div>
                            <div style="width: 140px;display: inline-block;">
                                <el-form-item
                                    class="spe-item spe-label"
                                    label-width="30px"
                                    label="+"
                                    prop="stake2"
                                >
                                    <el-input v-model.trim="item.stake2" maxlength="3" :disabled="!item.stake1" placeholder="请输入" />
                                </el-form-item>
                            </div>
                        </template>
                        <!-- 桩号范围 -->
                        <template v-if="item.locationType === 2">
                            <div style="padding-left: 14px;width: 168px;display: inline-block;">
                                <el-form-item label="" prop="startStake1" label-width="0">
                                    <el-input
                                        v-model.trim="item.startStake1"
                                        placeholder="请输入"
                                        maxlength="3"
                                        @change="item.startStake2 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </div>
                            <div style="width: 140px;display: inline-block;">
                                <el-form-item
                                    class="spe-item spe-label"
                                    label-width="30px"
                                    label="+"
                                    prop="startStake2"
                                >
                                    <el-input v-model.trim="item.startStake2" :disabled="!item.startStake1" maxlength="3" placeholder="请输入" />
                                </el-form-item>
                            </div>
                            <div style="width: 208px;display: inline-block;">
                                <el-form-item class="spe-item spe-label" label-width="40px" label="~" prop="endStake1">
                                    <el-input
                                        v-model.trim="item.endStake1"
                                        placeholder="请输入"
                                        maxlength="3"
                                        @change="item.endStake2 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </div>
                            <div style="width: 140px;display: inline-block;">
                                <el-form-item
                                    class="spe-item spe-label"
                                    label-width="30px"
                                    label="+"
                                    prop="endStake2"
                                >
                                    <el-input v-model.trim="item.endStake2" maxlength="3" :disabled="!item.endStake1" placeholder="请输入" />
                                </el-form-item>
                            </div>
                        </template>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="完成工程量" prop="detailList">
                            <BaseButton plain @click="handleSelectProject(item, index)">选择工程名称</BaseButton>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" style="margin-bottom: 16px;">
                        <BaseTable ref="table" :columns="columns" :data="item.detailList">
                            <template #header="{ scope: { column } }">
                                <span> <i class="required-start">*</i> {{ column.label }} </span>
                            </template>

                            <template #quantity="{ scope: { row, $index } }">
                                <el-input v-model.trim="row.quantity" type="number" clearable style="width: 140px;" :placeholder="row.quantityPlaceholder" @blur="handleValidateQuyantityOne(row, $index)" />
                                <!-- unitSymbol为下面三种单位的才显示计算说明 -->
                                <BaseButton
                                    v-if="row.unitCode === 'm' || row.unitCode === 'm2' || row.unitCode === 'm3'"
                                    style="width: 116px;margin-left: 8px;margin-right: 0;"
                                    plain
                                    @click="handleComputeDes(row)"
                                >
                                    填写计算说明
                                </BaseButton>
                            </template>
                            <template #remark="{ scope: { row } }">
                                <el-input v-model.trim="row.remark" type="textarea" autosize clearable maxlength="100" show-word-limit placeholder="请输入" class="spe-input" />
                            </template>
                            <template #handle="{ scope: { $index } }">
                                <BaseButton type="text" color="danger" @click="handleDeleteProject(item, $index)"> 移除 </BaseButton>
                            </template>
                        </BaseTable>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item>
                            <div slot="label" style="display: inline-block;">
                                <span>施工前照片</span>
                                <el-tooltip effect="dark" content="最多上传9个文件，单个文件最多50M，支持：.jpg .jpeg .png 格式。" placement="top">
                                    <i class="el-icon-info"></i>
                                </el-tooltip>
                            </div>
                            <ImageUpload ref="beforeImageUpload"  :key="index + '1'" :list="item.customBeforePhotos" :size="50" :limit="9" :over="beforeUploadOver"></ImageUpload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item>
                            <div slot="label" style="display: inline-block;">
                                <span>施工后照片</span>
                                <el-tooltip effect="dark" content="最多上传9个文件，单个文件最多50M，支持：.jpg .jpeg .png 格式。" placement="top">
                                    <i class="el-icon-info"></i>
                                </el-tooltip>
                            </div>
                            <ImageUpload ref="afterImageUpload" :key="index + '2'" :list="item.customAfterPhotos" :limit="9" :over="afterUploadOver"></ImageUpload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="简图、计算式、说明等">
                            <el-input
                                v-model="item.moreInstructions"
                                type="textarea"
                                :autosize="{ minRows: 3, maxRows: 4}"
                                placeholder="请输入"
                                maxlength="200"
                                show-word-limit
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </CardBox>
        
        <!-- 选择工程名称 -->
        <ProjectListDialog :id="id" ref="projectListDialog" @success="getTableList"></ProjectListDialog>
        <ComputeDesDialog ref="computeDesDialog" @success="getComputeDesData"></ComputeDesDialog>
    </div>
</template>

<script>
import { DirectionTwoWayOptions } from '@/config/constants'
import { uniqueId } from 'lodash-es'
import reconfirm from '@/utils/reconfirm'
import ProjectListDialog from './ProjectListDialog'
import ComputeDesDialog from './ComputeDesDialog'
import { isNumber2 } from '@/utils/validate'

export default {
    name: 'RecordAddCardList',
    components: {
        ProjectListDialog,
        ComputeDesDialog
    },
    props: {
        id: {
            type: [String, Number],
            default: ''
        },
        data: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            directionOptions: DirectionTwoWayOptions,
            cardList: [
                {
                    fid: uniqueId(),
                    locationType: 1,
                    detailList: [],
                    direction: '',
                    locationDescription: '',
                    stake1: '',
                    stake2: '',
                    startStake1: '',
                    startStake2: '',
                    endStake1: '',
                    endStake2: '',
                    customBeforePhotos: [], // 前端是数组，后端是字符串，所以重新定义个字段
                    customAfterPhotos: [],
                }
            ],
            rules: {
                locationType: [{ required: true, message: '请选择', trigger: 'change' }],
                direction: [{ required: true, message: '请选择', trigger: 'change' }],
                locationDescription: [{ required: true, message: '请输入', trigger: 'blur' }],
                stake1: [{ required: true, message: '请输入', trigger: 'blur' }],
                stake2: [{ required: true, message: '请输入', trigger: 'blur' }],
                startStake1: [{ required: true, message: '请输入', trigger: 'blur' }],
                startStake2: [{ required: true, message: '请输入', trigger: 'blur' }],
                endStake1: [{ required: true, message: '请输入', trigger: 'blur' }],
                endStake2: [{ required: true, message: '请输入', trigger: 'blur' }],
                detailList: [{ required: true, message: '请选择', trigger: 'change' }]
            },
            columns: Object.freeze([
                {
                    attrs: {
                        prop: 'number',
                        label: '序号',
                        width: '70',
                        type: 'index'
                    }
                },
                {
                    attrs: {
                        prop: 'listSubitemCode',
                        label: '清单子目编码',
                        width: '180',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'listSubitemName',
                        label: '清单子目名称（工程名称）',
                        width: '220',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'unitSymbol',
                        label: '单位',
                        width: '100',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'quantity',
                    headerSlot: 'header',
                    attrs: {
                        prop: 'quantity',
                        label: '完成数量',
                        width: '300'
                    }
                },
                {
                    slot: 'remark',
                    attrs: {
                        prop: 'remark',
                        label: '备注',
                        'min-width': '120',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'handle',
                    attrs: {
                        label: '操作',
                        width: '120',
                        fixed: 'right'
                    }
                }
            ]),
            cardActiveIndex: 0,
            beforeUploadOver: false,
            afterUploadOver: false,
            tableActiveRowIndex: 0
        }
    },
    watch: {
        data: {
            handler(val) {
                if (Array.isArray(val) && val.length > 0) {
                    // 这里要深拷贝一次，否则会出现表格里的输入框输入文字后自动失去焦点
                    const data = JSON.parse(JSON.stringify(val))
                    this.cardList = data.map(item => {
                        if (item.locationType === 1) {
                            const [stake1, stake2] = item.startStakeNo.replace('K', '').split('+')
                            item.stake1 = stake1
                            item.stake2 = stake2
                        }
                        if (item.locationType === 2) {
                            const [startStake1, startStake2] = item.startStakeNo.replace('K', '').split('+')
                            const [endStake1, endStake2] = item.endStakeNo.replace('K', '').split('+')
                            
                            item.startStake1 = startStake1
                            item.startStake2 = startStake2
                            item.endStake1 = endStake1
                            item.endStake2 = endStake2
                        }
                        
                        // 处理下编辑时，完成数量的小数验证
                        item.detailList = item.detailList.map(m => {
                            let quantityPlaceholder = ''
                            if (m.decimalPlace === 0) {
                                quantityPlaceholder = '保留整数'
                            } else {
                                quantityPlaceholder = `可保留${m.decimalPlace}位小数`
                            }
                            return {
                                ...m,
                                quantityPlaceholder
                            }
                        })
                        // this.$set(item, 'customBeforePhotos', item.beforePhotos ? JSON.parse(item.beforePhotos) : [])
                        // this.$set(item, 'customAfterPhotos', item.afterPhotos ? JSON.parse(item.afterPhotos) : [])
                        item.customBeforePhotos = item.beforePhotos ? JSON.parse(item.beforePhotos) : []
                        item.customAfterPhotos = item.afterPhotos ? JSON.parse(item.afterPhotos) : []
                        return {
                            ...item,
                            fid: uniqueId()
                        }
                    })
                    
                    console.log('this.cardList>>>', this.cardList)
                }
            },
            deep: true,
            immediate: true
                
        }
    },
    methods: {
        getComputeDesData(data) {
            // 把data赋值给tableActiveRow
            for (const key in data) {
                if (Object.hasOwnProperty.call(data, key)) {
                    this.tableActiveRow[key] = data[key]
                }
            }
            const { unitCode } = this.tableActiveRow
            if (unitCode === 'm') {
                this.tableActiveRow.quantity = data.length
            }
            if (unitCode === 'm2') {
                this.tableActiveRow.quantity = data.area
            }
            if (unitCode === 'm3') {
                this.tableActiveRow.quantity = data.volume
            }
        },
        handleComputeDes(row) {
            this.tableActiveRow = row
            let length = row.length || ''
            if (row.unitCode === 'm') {
                length = row.quantity
            }
            this.$refs['computeDesDialog'].open({
                length,
                width: row.width || '',
                height: row.height || '',
                area: row.area || '',
                volume: row.volume || ''
            })
        },
        getTableList(data) {
            const list = data.map(item => {
                let quantityPlaceholder = ''
                if (item.decimalPlace === 0) {
                    quantityPlaceholder = '保留整数'
                } else {
                    quantityPlaceholder = `可保留${item.decimalPlace}位小数`
                }
                return {
                    ...item,
                    quantityPlaceholder
                }
            })
            this.cardList[this.cardActiveIndex].detailList.push(...list)
        },
        handleDelete(index) {
            reconfirm({
                isPromise: false,
                callback: () => {
                    this.cardList.splice(index, 1)
                }
            })
        },
        handleDeleteProject(item, index) {
            reconfirm({
                isPromise: false,
                callback: () => {
                    item.detailList.splice(index, 1)
                }
            })
        },
        handleSelectProject(item, index) {
            this.cardActiveIndex = index
            const ids = item.detailList.map((item) => item.id)
            this.$refs['projectListDialog'].open(ids)
        },
        validate() {
            return new Promise((resolve, reject) => {
                const list = []
                const validas = []
                this.$refs['form'].forEach((item, index) => {
                    list.push(
                        new Promise((resolve) => {
                            item.validate((valida) => {
                                validas.push(valida)
                                resolve()
                            })
                        })
                    )
                })
                Promise.all([...list])
                    .then(() => {
                        const res = !validas.some((item) => item === false)
                        // 如果验证都通过，才返回true
                        if (res && this.validateTableList() && this.validateQuantities() && this.validateImgList()) {
                            resolve(true) 
                        } else {
                            resolve(false) 
                        }
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        },
        handleAdd() {
            this.cardList.push({
                fid: uniqueId(),
                locationType: 1,
                detailList: [],
                direction: '',
                locationDescription: '',
                stake1: '',
                stake2: '',
                startStake1: '',
                startStake2: '',
                endStake1: '',
                endStake2: '',
                customBeforePhotos: [],
                customAfterPhotos: [],
            })
            this.$message.success('新增分组成功')
        },
        getData() {
            this.$refs.beforeImageUpload.forEach((item, index) => {
                console.log('图片>>>', item.imgList)
                const imgList = (item.imgList || []).filter(Boolean).map((item) => {
                    return {
                        name: item.name,
                        url: item.response ? item.response.data.objectUrl : item.url
                    }
                })
                this.cardList[index].beforePhotos = JSON.stringify(imgList)
            })
            this.$refs.afterImageUpload.forEach((item, index) => {
                console.log('图片2>>>', item.imgList)
                // item.imgList可能是[null, null]这样的形式
                const imgList = (item.imgList || []).filter(Boolean).map((item) => {
                    return {
                        name: item.name,
                        url: item.response ? item.response.data.objectUrl : item.url
                    }
                })
                this.cardList[index].afterPhotos = JSON.stringify(imgList)
            })
            // 处理下桩号
            this.cardList.forEach(item => {
                if (item.locationType === 1) {
                    item.startStakeNo = `K${item.stake1}+${item.stake2}`
                    item.endStakeNo = ''
                }
                if (item.locationType === 2) {
                    item.startStakeNo = `K${item.startStake1}+${item.startStake2}`
                    item.endStakeNo = `K${item.endStake1}+${item.endStake2}`
                }
                if (item.locationType === 3) {
                    item.endStakeNo = ''
                }
            })
            return this.cardList
        },
        validateImgList() {
            const allImgList = []
            this.$refs.beforeImageUpload.forEach((item, index) => {
                const imgList = (item.imgList || []).filter(Boolean).map((item) => {
                    return {
                        name: item.name,
                        url: item.response ? item.response.data.objectUrl : item.url
                    }
                })
                allImgList.push(...imgList)
            })
            this.$refs.afterImageUpload.forEach((item, index) => {
                // item.imgList可能是[null, null]这样的形式
                const imgList = (item.imgList || []).filter(Boolean).map((item) => {
                    return {
                        name: item.name,
                        url: item.response ? item.response.data.objectUrl : item.url
                    }
                })
                allImgList.push(...imgList)
            })
            if (allImgList.length === 0) {
                this.$message.error('请至少上传一张施工前或施工后图片！')
                return false
            }
            return true
        },
        validateTableList() {
            let isValid = true
            for (let index = 0; index < this.cardList.length && isValid; index++) {
                const itemList = this.cardList[index].detailList
                if (itemList.length === 0) {
                    this.$message.error(`请至少选择一个工程（分组${index + 1}）！`)
                    isValid = false
                    break 
                }
            }
            return isValid
        },
        validQuantity(value, decimalPlace) {
            const regex = this.createDecimalRegex(decimalPlace)
            if (!regex.test(value)) {
                return false
            } else {
                return true
            }
        },
        createDecimalRegex(places) {
            if (places === 0) {
                return /^\d+$/
            }
            // 生成对应位数小数的正则表达式字符串
            const decimalPart = `(?:\\.(\\d{1,${places}}))?`
            const regexStr = `^\\d+${decimalPart}$`            
            return new RegExp(regexStr)
        },
        validateQuantities() {
            let isValid = true
            for (let index = 0; index < this.cardList.length && isValid; index++) {
                const itemList = this.cardList[index].detailList
                for (let i = 0; i < itemList.length && isValid; i++) {
                    const m = itemList[i]
                    if (!m.quantity) {
                        this.$message.error(`分组${index + 1}完成数量(序号${i + 1})不能为空！`)
                        isValid = false
                        break // 验证未通过，跳出内层循环
                    } else if (!this.validQuantity(Number(m.quantity), m.decimalPlace)) {
                        this.$message.error(`分组${index + 1}完成数量(序号${i + 1})格式错误！`)
                        isValid = false
                        break // 验证未通过，跳出内层循环
                    }
                }
            }
            return isValid
        },
        handleValidateQuyantityOne(row, i) {
            console.log(55866)
            if (!row.quantity) {
                return
            } else if (!this.validQuantity(Number(row.quantity), row.decimalPlace)) {
                this.$message.error(`完成数量(序号${i + 1})格式错误！`) 
            }
        },
        tableListValidate() {
            const list = []
            this.$refs.culvertBridgeTable.forEach((item) => {
                item.tableList.forEach((item) => {
                    const hasValue = Object.values(item).some((m) => {
                        if (Array.isArray(m)) {
                            if (m.length > 0) {
                                return true
                            } else {
                                return false
                            }
                        } else if (Object.prototype.toString.call(m) === '[object Object]') {
                            if (Object.keys.length > 0) {
                                return true
                            } else {
                                return false
                            }
                        } else {
                            return !!m
                        }
                    })
                    if (hasValue) {
                        if (item.description) {
                            list.push(true)
                        } else {
                            list.push(false)
                        }
                    } else {
                        list.push(true)
                    }
                })
            })
            const res = list.some((item) => item === false)
            return res
        }
    }
}
</script>

<style lang="scss" scoped>
.spe-item {
    ::v-deep {
        .el-form-item__label {
            text-align: center;
            padding: 0;
            &::before {
                display: none;
            }
        }
        .el-input,
        .el-input__inner {
            min-width: auto !important;
        }
    }
}
.required-start {
    color: #e50834;
    margin-right: 4px;
    font-style: normal;
}
</style>
